﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace HTSwitchServerNamespace.Util
{
    class UDPConnection
    {
        public UDPConnection()
        { }

        public string enviarRecibirDatosUDP(string host, int port,string message)
        {
            string returnData = null;
            UdpClient udpClient = new UdpClient();
            
            try
            {
                CLogger.Append("[enviarRecibirDatosUDP] HOST: " + host +" - PORT: "+port.ToString() + " - MSG: "+message, CLogger.INFO);

                udpClient.Connect(host, port);


                // Sends a message to the host to which you have connected.
                Byte[] sendBytes = Encoding.ASCII.GetBytes(message);


                udpClient.Send(sendBytes, sendBytes.Length);

                // Sends a message to a different host using optional hostname and port parameters.
            
                //IPEndPoint object will allow us to read datagrams sent from any source.
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

                
                // Blocks until a message returns on this socket from a remote host.
                Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
                returnData = Encoding.ASCII.GetString(receiveBytes);

                // Uses the IPEndPoint object to determine which of these two hosts responded.
                CLogger.Append("[enviarRecibirDatosUDP] DATA RECEIVED: " + returnData.ToString(), CLogger.COMM);
                CLogger.Append("[enviarRecibirDatosUDP] This message was sent from " + RemoteIpEndPoint.Address.ToString() + " on their port number " + RemoteIpEndPoint.Port.ToString(), CLogger.COMM);

            }
            catch (Exception e)
            {

                CLogger.Append("[enviarRecibirDatosUDP]" + e.ToString(), CLogger.ERROR);

            }
            finally
            {
                udpClient.Close();
                //udpClientB.Close();
            }
            return returnData.ToString();
        }
    }
}
